package com.openthinks.joyniproject.utils;

/**
 * 对文件的操作类
 * @author ZhangWenLong
 *
 */
public class FileHandler {
    /**
     * 获取文件的扩展名(不包含.)
     * 
     * @param fileName
     * @return
     */
    public static String getExtention(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if (pos == -1 || pos == fileName.length() - 1) {
        	return "";
        }
        return fileName.substring(pos + 1).toLowerCase();
    }
    
    /**
     * 获取不包含后缀的文件名
     * @param path
     * @return
     */
    public static String parseFileNameNoContainExtention(String path) {
    	
    	String fileName = FileHandler.parseFileName(path);
		int pos = fileName.lastIndexOf(".");
		if (pos == -1 || pos == fileName.length() - 1) {
			return fileName;
		}
		
		return fileName.substring(0, pos);
    }
    
    /**
	 * 解析文件名. 根据文件完整路径获取文件名,支持Windows及Linux路径格式
	 * @param path
	 * 			文件完整路径
	 * @return
	 * 			文件名
	 */
	public static String parseFileName(String path) {
		
		String[] sources = path.replaceAll("\\\\","/").split("/");
		String fileName = null;
		
		if (sources.length > 1) {
			fileName = sources[sources.length - 1];
		} else {
			fileName = path;
		}
		
		return fileName;
	}
	
	/**
	 * 解析文件名. 根据文件完整路径获取文件目录,支持Windows及Linux路径格式
	 * @param path
	 * 			文件完整路径
	 * @return
	 * 			文件名
	 */
	public static String parseFileDirectory(String path) {
		
		String[] sources = path.replaceAll("\\\\","/").split("/");
		String fileDirectory = "";
		
		if (sources.length > 1) {
			for (int i = 0; i < sources.length -1; i++) {
				fileDirectory += (sources[i] + "/");
			}
		} else {
			fileDirectory = path;
		}
		
		return fileDirectory;
	}
}
